package org.ws.lifebacklog.db;

import java.util.ArrayList;
import java.util.List;

import org.ws.lifebacklog.event.ExceptionEvent;
import org.ws.lifebacklog.exception.DatabaseException;
import org.ws.lifebacklog.util.AppConfig;
import org.ws.lifebacklog.util.DatabaseUtil;
import org.ws.lifebacklog.util.Logger;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
	public final static String DATABASE_NAME = "lifebacklog2.db";
	private final Context mContext;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DatabaseUtil.getDbVersion(context.getAssets()));
		mContext = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Logger.w(getClass(), "Create new  database");
		onUpgrade(db, 1, 1);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		newVersion = upgrade(db, oldVersion);
		Logger.w(getClass(), "Upgrading database from version " + oldVersion + " to " + newVersion);
	}

	private int upgrade(SQLiteDatabase db, int version) {
		List<String> sqls = new ArrayList<String>();
		int newVersion = 0;
		try {
			newVersion = DatabaseUtil.getSQLScripts(mContext.getAssets(), sqls, version);
			if (newVersion > version && sqls.size() > 0) {
				excecteScripts(db, sqls);
				db.setVersion(newVersion);
				AppConfig.getInstance().setDbVersion(newVersion);
				Logger.i(getClass(), "Database had been updated.");
			} else {
				db.setVersion(version);
			}
		} catch (Exception e) {
			newVersion = 0;
			mContext.sendBroadcast(new ExceptionEvent(ExceptionEvent.ERR_SQL_UPGRADE));
		}
		return newVersion;

	}

	private void excecteScripts(SQLiteDatabase db, List<String> scripts) throws DatabaseException {
		try {
			db.beginTransaction();
			for (String sql : scripts) {
				db.execSQL(sql);
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			throw new DatabaseException(e);
		} finally {
			db.endTransaction();
		}
	}

	/**
	 * 
	 */
	public TaskDao getTaskDao() {
		return new TaskDao(this);
	}
}
